package controller

import (
	"conf"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
	"runtime/debug"
	"smart_home/task/models"
	"smart_home/task/system"
	"strings"
	"time"
	"tools"
)

func GetUseModeTiming() error {
	ls := models.GetTimingUM()
	for _, v := range ls {
		go system.Producter(v, DelManual)
	}
	return nil
}

func GetUseModeManual() error {
	ls := models.GetManualUM()
	for _, v := range ls {
		go system.Producter(v, DelManual)
	}
	return nil
}

func DelManual(data interface{}) {
	// 捕抓错误 防止mqtt客户端死掉
	defer func() {
		if err := recover(); err != nil {
			logs.Error("panic error:", err)
			debug.PrintStack()
		}
	}()

	var (
		um     *models.UseMode
		domain string
		url    string
		st     string
	)

	st = conf.String("st")

	um = data.(*models.UseMode)
	um.IsActivate = 0
	models.UpdateUseModeStatus(um)

	// 推送到设备
	if len(um.Task) > 0 {
		domain = conf.String("domain", conf.String("runmode"))

		for _, v := range um.Task {
			// after
			fmt.Println(v)
			<-time.After(time.Duration(v.After) * time.Second)
			go func(tk *models.UseModeTasks) {
				act := "open"
				if tk.State == 0 {
					act = "close"
				}
				url = domain + "/v2/switch/" + act + "/" + tk.Sta
				res, err := httplib.Get(url).Header("st", st).Header("suid", um.UserId).String()
				if err != nil {
					fmt.Println(err)
					logs.Error("DelManual error:", err)
				} else {
					fmt.Println(res)
					logs.Debug("DelManual:", res)
				}
			}(v)
		}
	}

	content := strings.Replace(um.Name, "模式", "", 1) + "模式" + "执行完毕"
	// 写入日志
	models.AddMessage(um.UserId, "执行通知", content)

	if um.IsPush == 1 {
		// 推送消息
		err := tools.NewJpush().SetAlias(um.UserId).SetAlert(content).Jump("message").Send()
		logs.Debug("use_mode info:", um)
		if err != nil {
			logs.Error(err)
		}
		fmt.Println("err:", err)
	}
}
